package com.example.demo.controller;

import cn.hutool.json.JSONObject;
import com.example.demo.annotation.PassToken;
import com.example.demo.annotation.UserLoginToken;
import com.example.demo.common.BaseResponse;
import com.example.demo.common.RespGenerator;
import com.example.demo.model.bo.UserDetailBO;
import com.example.demo.model.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author KUBUB
 */
@Api(tags = "用户操作类")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @PassToken
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public BaseResponse<?> login(@RequestBody UserDetailBO sourceUser) {
        JSONObject jsonObject = new JSONObject();
        User user = new User();
        BeanUtils.copyProperties(sourceUser,user);
        User userForBase = userService.selectByName(user);
        // 如果用户不存在，则返回错误
        if (userForBase == null) {
            jsonObject.append("message", "登录失败，用户不存在");
        } else {
            // 如果用户密码错误，则返回错误
            if (!StringUtils.equals(userForBase.getPassword(), user.getPassword())) {
                jsonObject.append("message", "登录失败，密码错误");
            } else {
                String token = TokenUtils.getToken(userForBase);
                // 清空用户密码
                userForBase.setPassword("");
                jsonObject.append("token", token);
                jsonObject.append("user", userForBase);
            }
        }
        return RespGenerator.success(userForBase);
    }

    @UserLoginToken
    @ApiOperation(value = "登录测试")
    @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header")
    @GetMapping("/getMessage")
    public Object getMessage() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.append("message", "你已经通过验证");
        return jsonObject;
    }


}
